import { create } from 'zustand';
import { devtools, persist, createJSONStorage } from 'zustand/middleware';
import { immer } from 'zustand/middleware/immer';

export type LayoutType = 'classic' | 'hybrid' | 'top';

type AppState = {
  title: string;
  collapse: boolean;
  isTagView: boolean;
  isFooter: boolean;
  pageLoading: boolean;
  layout: LayoutType;
  dynamicRouter: boolean;
  primary: string;
  isDark: boolean;
  colors: Array<string>;
};

type AppAction = {
  setCollapse: (bool?: boolean) => void;
  setLayout: (layout: LayoutType) => void;
  setTagView: (bool?: boolean) => void;
  setFooter: (bool?: boolean) => void;
};

const immerResult = immer<AppState & AppAction>(set => ({
  // 项目名称
  title: import.meta.env.VITE_APP_NAME,
  // 是否使用动态路由
  dynamicRouter: false,
  //是否折叠菜单
  collapse: false,
  // 是否显示footer
  isFooter: true,
  // 是否显示tagView
  isTagView: true,
  //是否暗黑模式
  isDark: false,
  // 主题色
  primary: '#15a1a1',
  // 全局加载
  pageLoading: false,
  // 预定义主题颜色
  colors: [
    '#15a1a1',
    '#409eff',
    '#DAA96E',
    '#722ed1',
    '#27ae60',
    '#ff5c93',
    '#e74c3c',
    '#fd726d',
    '#f39c12',
    '#9b59b6',
  ],
  // 页面整体布局
  layout: 'classic',
  setCollapse: collapse =>
    set(state => {
      if (collapse) {
        state.collapse = collapse;
      } else {
        state.collapse = !state.collapse;
      }
    }),
  setLayout: layout =>
    set(state => {
      if (state.layout !== layout) {
        state.layout = layout;
      }
    }),
  setTagView: isTagView =>
    set(state => {
      if (isTagView) {
        state.isTagView = isTagView;
      } else {
        state.isTagView = !state.isTagView;
      }
    }),
  setFooter: isFooter =>
    set(state => {
      if (isFooter) {
        state.isFooter = isFooter;
      } else {
        state.isFooter = !state.isFooter;
      }
    }),
}));

const persistResult = persist(immerResult, {
  name: 'app-store',
  storage: createJSONStorage(() => localStorage),
  partialize: state => ({
    layout: state.layout,
    isDark: state.isDark,
    primary: state.primary,
    isFooter: state.isFooter,
    isTagView: state.isTagView,
  }),
});

const devtoolsResult = devtools(persistResult, {
  name: 'App Store',
  enabled: true,
});

export const useAppStore = create<AppState & AppAction>()(devtoolsResult);
